package com.qiyuan.boot.utils.oss;

import cn.hutool.core.util.IdUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.qiyuan.boot.utils.BusinessException;
import com.qiyuan.boot.utils.DateUtils;
import com.qiyuan.boot.utils.StringUtils;
import com.qiyuan.boot.utils.entity.UploadResult;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 腾讯云存储策略
 *
 * @author qiyuan
 */
public class QcloudOssUtil{

	private COSClient client;
	//域名
	private String endpoint;
	//前缀
	private String prefix;
	//ACCESS_KEY
	private String accessKey;
	//SECRET_KEY
	private String secretKey;
	//存储空间名
	private String bucketName;
	//存储区域
	private String region;
	//是否https（Y=是,N=否）
	private String isHttps;
	//内网地址
	private String intranet;
	//内网地址状态
	private String intranetStatus;


	public QcloudOssUtil(String endpoint,String prefix,String accessKey,String secretKey,String bucketName,String region,String isHttps,String intranet,String intranetStatus){
		this.endpoint = endpoint;
		this.prefix = prefix;
		this.accessKey = accessKey;
		this.secretKey = secretKey;
		this.bucketName = bucketName;
		this.region = region;
		this.isHttps = isHttps;
		this.intranet = intranet;
		this.intranetStatus = intranetStatus;
	}

	public void init() {
		try {
			COSCredentials credentials = new BasicCOSCredentials(accessKey, secretKey);
			// 初始化客户端配置
			ClientConfig clientConfig = new ClientConfig();
			// 设置bucket所在的区域，华南：gz 华北：tj 华东：sh
			clientConfig.setRegion(new Region(region));
			if ("Y".equals(isHttps)) {
				clientConfig.setHttpProtocol(HttpProtocol.https);
			} else {
				clientConfig.setHttpProtocol(HttpProtocol.http);
			}
			client = new COSClient(credentials, clientConfig);
			createBucket();
		} catch (Exception e) {
			throw new BusinessException("腾讯云存储配置错误! 请检查系统配置:[" + e.getMessage() + "]");
		}
	}

	public void createBucket() {
		try {
			if (client.doesBucketExist(bucketName)) {
				return;
			}
			CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
			createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
			client.createBucket(createBucketRequest);
		} catch (Exception e) {
			throw new BusinessException("创建Bucket失败, 请核对腾讯云配置信息:[" + e.getMessage() + "]");
		}
	}

	public String getServiceType() {
		return "qcloud";
	}

	public UploadResult upload(byte[] data, String path, String contentType) {
		return upload(new ByteArrayInputStream(data), path, contentType);
	}

	public UploadResult upload(InputStream inputStream, String path, String contentType) {
		try {
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentType(contentType);
			client.putObject(new PutObjectRequest(bucketName, path, inputStream, metadata));
		} catch (Exception e) {
			throw new BusinessException("上传文件失败，请检查腾讯云配置信息:[" + e.getMessage() + "]");
		}
		return new UploadResult().setUrl(getEndpointLink() + "/" + path).setFilename(path).setIntranetUrl(intranet + "/" + path).setIntranetStatus(intranetStatus);
	}

	public void delete(String path) {
		path = path.replace(getEndpointLink() + "/", "");
		try {
			client.deleteObject(new DeleteObjectRequest(bucketName, path));
		} catch (Exception e) {
			throw new BusinessException("上传文件失败，请检腾讯云查配置信息:[" + e.getMessage() + "]");
		}
	}

	public UploadResult uploadSuffix(byte[] data, String suffix, String contentType) {
		return upload(data, getPath(prefix, suffix), contentType);
	}

	public UploadResult uploadSuffix(InputStream inputStream, String suffix, String contentType) {
		return upload(inputStream, getPath(prefix, suffix), contentType);
	}

	public String getEndpointLink() {
		StringBuilder sb = new StringBuilder(endpoint);
		if (StringUtils.containsAnyIgnoreCase(endpoint, "http://")) {
			sb.insert(7, bucketName + ".");
		} else if (StringUtils.containsAnyIgnoreCase(endpoint, "https://")) {
			sb.insert(8, bucketName + ".");
		} else {
			throw new BusinessException("Endpoint配置错误");
		}
		return sb.toString();
	}

	public String getPath(String prefix, String suffix) {
		// 生成uuid
		String uuid = IdUtil.fastSimpleUUID();
		// 文件路径
		String path = DateUtils.datePath() + "/" + uuid;
		if (StringUtils.isNotBlank(prefix)) {
			path = prefix + "/" + path;
		}
		return path + suffix;
	}
}
